import cryptoJs from 'crypto-js'
const AES_KEY = '8NONwyJtHesysWpM'

export default {
  generate(uname, pword) {
    uname = uname.replace(/\\%/g, '')
    pword = pword.replace(/\\%/g, '')
    uname = uname.replace(/\\</g, '')
    pword = pword.replace(/\\</g, '')
    uname = uname.replace(/\\>/g, '')
    pword = pword.replace(/\\>/g, '')

    return this.Encrypt(uname + ',' + pword)
  },

  Encrypt(content) {
    const key = cryptoJs.enc.Utf8.parse(AES_KEY)
    const srcs = cryptoJs.enc.Utf8.parse(content)
    const encrypted = cryptoJs.AES.encrypt(srcs, key, {
      mode: cryptoJs.mode.ECB,
      padding: cryptoJs.pad.Pkcs7
    })
    return encrypted.toString()
  },

  Decrypt(content) {
    const key = cryptoJs.enc.Utf8.parse(AES_KEY)
    const decrypt = cryptoJs.AES.decrypt(content, key, {
      mode: cryptoJs.mode.ECB,
      padding: cryptoJs.pad.Pkcs7
    })
    return cryptoJs.enc.Utf8.stringify(decrypt).toString()
  },

  checkPermission(permissions, roles) {
    if (!permissions || permissions.length === 0) {
      return false
    }

    roles = roles || store.getters && store.getters.roles
    for (const permission of permissions) {
      for (let i = 0; i < roles.length; i++) {
        const permission_str = permission.split(':')
        const role_str = roles[i].split(':')
        for (let j = 0; j < role_str.length; j++) {
          if (permission_str[j] === '*') {
            return true
          } else if (permission_str[j] !== role_str[j]) {
            break
          }
        }
      }
    }

    return false
  }
}
